﻿using System;
using System.Web.UI.WebControls;
using Lapointe.WebPartPageHistory.ListEventReceivers;
using Microsoft.SharePoint;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace Lapointe.WebPartPageHistory.ApplicationPages
{
    public class ListSettingsPage : ListPageBase
    {
        protected RadioButton RadEnableNo;
        protected RadioButton RadEnableYes;
        protected RadioButton RadDependenciesYes;
        protected RadioButton RadDependenciesNo;
        protected InputFormSection EnableHistorySection;
        protected InputFormSection IncludeDependenciesSection;
        const string assembly = "Lapointe.WebPartPageHistory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3216c23aba16db08";
        const string className = "Lapointe.WebPartPageHistory.ListEventReceivers.SourceListEventReceiver";

        /// <summary>
        /// Handles the Click event of the BtnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected virtual void BtnSave_Click(object sender, EventArgs e)
        {
            if (EnableHistorySection.Visible)
            {
                if (RadEnableYes.Checked)
                {
                    AddEventReceiver(List, SPEventReceiverType.ItemCheckedIn);
                    AddEventReceiver(List, SPEventReceiverType.ItemUpdating);
                    AddEventReceiver(List, SPEventReceiverType.ItemUpdated);

                    List.RootFolder.Properties[HistoryHelper.PROP_INCLUDE_DEPENDENCIES_KEY] =
                        RadDependenciesYes.Checked.ToString();
                    List.RootFolder.Update();
                }
                else
                {
                    DeleteEventReceiver(List, SPEventReceiverType.ItemCheckedIn);
                    DeleteEventReceiver(List, SPEventReceiverType.ItemUpdating);
                    DeleteEventReceiver(List, SPEventReceiverType.ItemUpdated);
                }
            }

            SPUtility.Redirect(ListEditPageLayoutsRelativeUrl, SPRedirectFlags.RelativeToLayoutsPage, Context);
        }

        /// <summary>
        /// Called when the state of the radio button changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected virtual void OnEnableStateChanged(object sender, EventArgs e)
        {
            IncludeDependenciesSection.Visible = EnableHistorySection.Visible && RadEnableYes.Checked;
        }

        /// <summary>
        /// Raises the <see cref="OnLoad"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!IsPostBack)
            {
                if (!List.EnableVersioning)
                    throw new SPException("Versioning is not enabled.  You must enable versioning in order to store web part page changes.");

                EnableHistorySection.Visible = (List.BaseType == SPBaseType.DocumentLibrary);
                if (EnableHistorySection.Visible)
                {
                    RadEnableYes.Checked = EventReceiversAdded(List);
                    RadEnableNo.Checked = !RadEnableYes.Checked;
                }
                IncludeDependenciesSection.Visible = EnableHistorySection.Visible && RadEnableYes.Checked;
                if (IncludeDependenciesSection.Visible)
                {
                    RadDependenciesYes.Checked = HistoryHelper.IncludeDependencies(List);
                    RadDependenciesNo.Checked = !RadDependenciesYes.Checked;
                }
            }
        }

        /// <summary>
        /// Checks to see if any of the event receivers have been added.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        private static bool EventReceiversAdded(SPList list)
        {
            if (GetEventReceiver(list, SPEventReceiverType.ItemCheckedIn) != null ||
                GetEventReceiver(list, SPEventReceiverType.ItemUpdating) != null ||
                GetEventReceiver(list, SPEventReceiverType.ItemUpdated) != null)
                return true;
            return false;
        }

        /// <summary>
        /// Adds a SourceListEventReceiver event receiver to a list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="eventReceiverType">Type of the event receiver.</param>
        private static void AddEventReceiver(SPList list, SPEventReceiverType eventReceiverType)
        {
            if (GetEventReceiver(list, eventReceiverType) == null)
            {
                list.EventReceivers.Add(eventReceiverType, assembly, className);
            }
        }

        /// <summary>
        /// Gets the event receiver.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="eventReceiverType">Type of the event receiver.</param>
        /// <returns></returns>
        private static SPEventReceiverDefinition GetEventReceiver(SPList list, SPEventReceiverType eventReceiverType)
        {
            foreach (SPEventReceiverDefinition erd in list.EventReceivers)
            {
                if (erd.Assembly == assembly && erd.Class == className && erd.Type == eventReceiverType)
                {
                    return erd;
                }
            }
            return null;
        }

        /// <summary>
        /// Deletes the event receiver.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="eventReceiverType">Type of the event receiver.</param>
        private static void DeleteEventReceiver(SPList list, SPEventReceiverType eventReceiverType)
        {
            SPEventReceiverDefinition erd = GetEventReceiver(list, eventReceiverType);
            if (erd != null)
                erd.Delete();
        }

        /// <summary>
        /// Gets the rights required.
        /// </summary>
        /// <value>The rights required.</value>
        protected override SPBasePermissions RightsRequired
        {
            get
            {
                return (SPBasePermissions.EmptyMask | SPBasePermissions.ManageLists);
            }
        }
    }

 

}
